package com.vader.springcloud.controller;

import com.vader.springcloud.entities.CommonResult;
import com.vader.springcloud.entities.mapper.PaymentDO;
import com.vader.springcloud.lb.LoadBalance;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author kaivader
 */
@RestController
@RequestMapping("/consumer")
@Slf4j
public class OrderController {
    //    private final String PAYMENT_URL = "http://localhost:8001";
    private final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private DiscoveryClient discoveryClient;

    @Resource
    private LoadBalance balance;

    @GetMapping("/payment/insert")
    public CommonResult<PaymentDO> insert(PaymentDO paymentDO) {
        return restTemplate.postForObject(PAYMENT_URL + "/payment/insert", paymentDO, CommonResult.class);
    }

    @GetMapping("/payment/query/{id}")
    public CommonResult<PaymentDO> query(@PathVariable("id") Long id) {
        return restTemplate.getForObject(PAYMENT_URL + "/payment/query/" + id, CommonResult.class);
    }

    @GetMapping("/payment/lb")
    public String getLoadBalance() {
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        if (instances.isEmpty() || instances == null) {
            return null;
        }

        ServiceInstance serviceInstance = balance.instances(instances);
        return restTemplate.getForObject(serviceInstance.getUri() + "/payment/lb", String.class);
    }
}
